<template>
  <div class="app-container">
    <eHeader :query="query" />
    <BatchAssignOrder ref="batchAssignOrder" :data.sync="batchData" :sup-this="supThis" />
    <BatchSuggestOrder ref="batchEvaluteOrder" :data.sync="batchData" :sup-this="supThis" />
    <!--表格渲染-->
    <el-table v-loading="loading" :data="data" size="small" style="width: 100%;" @selection-change="selectionChangeHandler">
      <el-table-column type="selection" width="55" />
      <el-table-column :show-overflow-tooltip="true" prop="orderCode" label="工单编号" />
      <el-table-column prop="status" label="工单状态">
        <template slot-scope="scope">
          <div v-for="item in statusOptions" :key="item.id">
            <el-tag v-show="scope.row.status.toString() === item.value">{{ item.label }}</el-tag>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="orderSource" label="工单类型">
        <template slot-scope="scope">
          <div v-for="item in orderSourceOptions" :key="item.key">
            <span v-show="scope.row.orderSource.toString() === item.key">{{ item.display_name }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column :show-overflow-tooltip="true" label="客户名称">
        <template slot-scope="scope">
          <span v-if="scope.row.orderSource===1">{{ scope.row.taccident.customerName }}</span>
          <span v-if="scope.row.orderSource===2">{{ scope.row.task.customerName }}</span>
        </template>
      </el-table-column>
      <el-table-column :show-overflow-tooltip="true" label="供应商名称">
        <template slot-scope="scope">
          <span>{{ scope.row.supplierName }}</span>
        </template>
      </el-table-column>
      <!--
      <el-table-column :show-overflow-tooltip="true" label="报修内容">
        <template slot-scope="scope">
          <span v-if="scope.row.orderSource===1">{{ scope.row.taccident.faultDesc }}</span>
        </template>
      </el-table-column>
      <el-table-column :show-overflow-tooltip="true" label="报修时间">
        <template slot-scope="scope">
          <span v-if="scope.row.orderSource===1">{{ parseTime(scope.row.taccident.inputTime) }}</span>
        </template>
      </el-table-column>
      -->
      <el-table-column :show-overflow-tooltip="true" label="任务名称">
        <template slot-scope="scope">
          <span v-if="scope.row.orderSource===2">{{ scope.row.task.taskTitle }}</span>
        </template>
      </el-table-column>
      <el-table-column :show-overflow-tooltip="true" label="任务内容">
        <template slot-scope="scope">
          <span v-if="scope.row.orderSource===2">{{ scope.row.task.taskContent }}</span>
        </template>
      </el-table-column>
      <el-table-column :show-overflow-tooltip="true" label="详细地址">
        <template slot-scope="scope">
          <span v-if="scope.row.orderSource===2">{{ scope.row.task.taskAddr }}</span>
        </template>
      </el-table-column>
      <el-table-column :show-overflow-tooltip="true" label="要求到场时间">
        <template slot-scope="scope">
          <span v-if="scope.row.orderSource===2">{{ parseTime(scope.row.task.arriveTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column :show-overflow-tooltip="true" label="要求完成时间">
        <template slot-scope="scope">
          <span v-if="scope.row.orderSource===2">{{ parseTime(scope.row.task.finishTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column :show-overflow-tooltip="true" label="联系人" prop="linker">
        <template slot-scope="scope">
          <span v-if="scope.row.orderSource===2">{{ scope.row.task.linker }}</span>
        </template>
      </el-table-column>
      <el-table-column :show-overflow-tooltip="true" label="联系电话" prop="cellphone">
        <template slot-scope="scope">
          <span v-if="scope.row.orderSource===2">{{ scope.row.task.cellphone }}</span>
        </template>
      </el-table-column>
      <!--
      <el-table-column :show-overflow-tooltip="true" label="巡检要求">
        <template slot-scope="scope">
          <span v-if="scope.row.orderSource===3">{{ scope.row.inspection.planDesc }}</span>
        </template>
      </el-table-column>
      <el-table-column :show-overflow-tooltip="true" label="巡检时间">
        <template slot-scope="scope">
          <span v-if="scope.row.orderSource===3">{{ parseTime(scope.row.inspection.operateTime) }}</span>
        </template>
      </el-table-column>-->
      <!-- <el-table-column prop="serviceLevel" label="服务等级">
        <template slot-scope="scope">
          <div v-for="item in serviceLevels" :key="item.id">
            <el-tag v-show="scope.row.serviceLevel.toString() === item.value" >{{ item.label }}</el-tag>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="faultType" label="故障类型">
        <template slot-scope="scope">
          <div v-for="item in faultTypes" :key="item.id">
            <el-tag v-show="scope.row.faultType.toString() === item.value" >{{ item.label }}</el-tag>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="supplier" label="服务商"/>
      <el-table-column prop="assignOperator" label="指派人"/>
      <el-table-column :show-overflow-tooltip="true" prop="assignTime" label="指派时间">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.assignTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="acceptOperator" label="接单人"/>
      <el-table-column :show-overflow-tooltip="true" prop="acceptTime" label="接单时间">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.acceptTime) }}</span>
        </template>
      </el-table-column> -->
      <el-table-column v-if="checkPermission(['ADMIN','TWORKORDER_ALL','TWORKORDER_EDIT','TWORKORDER_DELETE'])" label="操作" width="180px" align="center">
        <template slot-scope="scope">
          <edit v-permission="['ADMIN','TWORKORDER_ALL','TWORKORDER_EDIT']" :data="scope.row" :sup-this="supThis" />
          <AssignOrder v-show="checkeAssignable(scope.row.status)" v-permission="['ADMIN','TWORKORDER_ALL','TWORKORDER_EDIT']" :data="scope.row" :sup-this="supThis" />
          <log-order v-permission="['ADMIN','TWORKORDER_ALL','TWORKORDER_EDIT']" :value="scope.row" :sup-this="supThis" />
          <SuggestOrder v-show="checkRevisitVisible(scope.row.status)" v-permission="['ADMIN','TWORKORDER_ALL','TWORKORDER_EDIT']" :data="scope.row" :sup-this="supThis" />
          <EvaluateOrder v-show="checkEvaluteVisible(scope.row.status)" v-permission="['ADMIN','TWORKORDER_ALL','TWORKORDER_EDIT']" :data="scope.row" :sup-this="supThis" />
          <el-popover
            :ref="scope.row.id"
            v-permission="['ADMIN','TWORKORDER_ALL','TWORKORDER_DELETE']"
            placement="top"
            width="180"
          >
            <p>确定删除本条数据吗？</p>
            <div style="text-align: right; margin: 0">
              <el-button size="mini" type="text" @click="$refs[scope.row.id].doClose()">取消</el-button>
              <el-button :loading="delLoading" type="primary" size="mini" @click="subDelete(scope.row.id)">确定</el-button>
            </div>
            <!--不能删除
            <el-button slot="reference" type="text" size="mini">删除</el-button>
            -->
          </el-popover>
        </template>
      </el-table-column>
    </el-table>
    <!--分页组件-->
    <el-pagination
      :total="total"
      style="margin-top: 8px;"
      layout="total, prev, pager, next, sizes"
      @size-change="sizeChange"
      @current-change="pageChange"
    />
  </div>
</template>

<script>
import { get } from '@/api/dictDetail'
import checkPermission from '@/utils/permission'
import initData from '@/mixins/initData'
import { del } from '@/api/tWorkOrder'
import { parseTime } from '@/utils/index'
import eHeader from './module/header'
import edit from './module/edit'
import LogOrder from './module/components/logOrder'
import SuggestOrder from './module/components/suggestOrder'
import AssignOrder from './module/components/assignOrder'
import BatchAssignOrder from './module/components/batchAssignOrder'
import EvaluateOrder from './module/components/evaluteOrder'
import BatchSuggestOrder from './module/components/batchEvaluteOrder'
import { checkeAssignable, checkRevisitVisible, checkEvaluteVisible, checkEvaluteEditable } from '@/api/data'

export default {
  components: { eHeader, edit, LogOrder, SuggestOrder, AssignOrder, EvaluateOrder, BatchAssignOrder, BatchSuggestOrder },
  mixins: [initData],
  data() {
    return {
      delLoading: false,
      supThis: this,
      statusOptions: [],
      serviceLevels: [],
      faultTypes: [],
      selections: [],
      batchData: {},
      orderSourceOptions: [
        { key: '1', display_name: '故障单' },
        { key: '2', display_name: '任务单' },
        { key: '3', display_name: '巡检单' }
      ]
    }
  },
  created() {
    this.$nextTick(() => {
      this.init()
      this.getDict('order_status')
      this.getDict('fault_type')
      this.getDict('service_level')
    })
  },
  methods: {
    parseTime,
    checkPermission,
    checkeAssignable,
    checkRevisitVisible,
    checkEvaluteVisible,
    checkEvaluteEditable,
    beforeInit() {
      this.url = 'api/tWorkOrder'
      const sort = 'id,desc'
      this.params = { page: this.page, size: this.size, sort: sort }
      const query = this.query
      if (query.orderCode) {
        this.params['orderCode'] = query.orderCode
      }
      if (query.status) {
        this.params['status'] = query.status
      }
      if (query.orderSource) {
        this.params['orderSource'] = query.orderSource
      }
      if (query.country) {
        this.params['country'] = query.country
      }
      if (query.province) {
        this.params['province'] = query.province
      }
      if (query.city) {
        this.params['city'] = query.city
      }
      if (query.county) {
        this.params['county'] = query.county
      }
      if (query.supplier) {
        this.params['supplier'] = query.supplier
      }
      if (query.customerId) {
        this.params['customerId'] = query.customerId
      }
      if (query.taskAddr) {
        this.params['taskAddr'] = query.taskAddr
      }
      return true
    },
    async getDict(name) {
      return new Promise((resolve, reject) => {
        get(name).then(res => {
          if (name === 'order_status') {
            this.statusOptions = res.content
          } else if (name === 'fault_type') {
            this.faultTypes = res.content
          } else {
            this.serviceLevels = res.content
          }
          resolve(res)
        }).catch(err => {
          reject(err)
        })
      })
    },
    subDelete(id) {
      this.delLoading = true
      del(id).then(res => {
        this.delLoading = false
        this.$refs[id].doClose()
        this.init()
        this.$notify({
          title: '删除成功',
          type: 'success',
          duration: 2500
        })
      }).catch(err => {
        this.delLoading = false
        this.$refs[id].doClose()
        console.log(err)
      })
    },
    // 选择改变
    selectionChangeHandler(val) {
      this.selections = val
    },
    batchDispatch() {
      if (this.selections.length > 0) {
        var lastcode = ''
        var lastcountry = ''
        var lastprovince = ''
        var lastcity = ''
        for (var index in this.selections) {
          const item = this.selections[index]
          if (!checkeAssignable(item.status)) {
            this.$notify({
              title: '工单不能重复派单',
              type: 'error',
              duration: 2500
            })
            return
          }
          if (lastcode !== '') {
            const i = item.orderCode.lastIndexOf('-')
            const prefix = item.orderCode.substring(0, i)
            console.log(prefix, lastcode)
            if (!lastcode.startsWith(prefix)) {
              this.$notify({
                title: '工单编号不是同一批次',
                type: 'error',
                duration: 2500
              })
              return
            }
            if (lastcountry !== item.country || lastcity !== item.city || lastprovince !== item.province) {
              this.$notify({
                title: '工单不是同一地区',
                type: 'error',
                duration: 2500
              })
              return
            }
          }
          lastcode = item.orderCode
          lastcountry = item.country
          lastprovince = item.province
          lastcity = item.city
        }
        this.batchData = { ...this.selections[0], selections: this.selections }
        console.log(this.batchData)
        this.$refs['batchAssignOrder'].to(this.batchData)
      } // >0
    }, // endf of batchDispatch
    batchEvaluate() {
      if (this.selections.length > 0) {
        var lasstSupplier = ''
        for (var index in this.selections) {
          const item = this.selections[index]
          if (!checkEvaluteEditable(item.status)) {
            this.$notify({
              title: '工单不能评价',
              type: 'error',
              duration: 2500
            })
            return
          }
          if (lasstSupplier !== '') {
            if (lasstSupplier !== item.supplier) {
              this.$notify({
                title: '工单不属于于同一供应商',
                type: 'error',
                duration: 2500
              })
              return
            }
          }
          lasstSupplier = item.supplier
        }
        this.batchData = { ...this.selections[0], selections: this.selections }
        console.log(this.batchData)
        this.$refs['batchEvaluteOrder'].to(this.batchData)
      } // >0
    } // endf of batchEvalute
  }
}
</script>

<style scoped>
</style>
